﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SolutionSettings;

namespace SolutionSettings_UnitTests {
    [TestClass]
    public class SettingsManagerTest {
        #region Mock ActivityLog
        private MockActivityLog ActivityLog;

        [TestInitialize]
        public void PrepareMockLog() {
            ActivityLog = new MockActivityLog();
            var mockListener = new ActivityLogTraceListener(ActivityLog);
            mockListener.Name = "MockListener";
            Trace.Listeners.Add(mockListener);
        }

        [TestCleanup]
        public void CloseMockLog() {
            Trace.Listeners.Remove("MockListener");
        }
        #endregion

        private SettingsManager NewManager(IFileSystem fs = null, ISettingsProvider sp = null) {
            return new SettingsManager(fs ?? new MockFileSystem(), sp ?? new DefaultSettingsProvider());
        }

        [TestMethod]
        [ExpectedException(typeof(InvalidOperationException))]
        public void TestRename_NoSolution() {
            NewManager().SolutionRenamed(null);
        }

        [TestMethod]
        [ExpectedException(typeof(InvalidOperationException))]
        public void TestQueryClose_NoSolution() {
            NewManager().CanSolutionClose();
        }

        [TestMethod]
        public void TestOpen_SolutionNoSettings() {
            var fs = new MockFileSystem();
            fs.Files.Add(new MockFile(@"X:\Test.sln", FileCreator.BlankSolution));
            ActivityLog.Clear();
            var manager = NewManager(fs: fs);

            var sln = new MockSolution(@"X:\Test.sln");
            manager.SolutionOpened(sln);

            Assert.AreSame(sln, manager.ActiveSolution, "ActiveSolution is not correct.");
            Assert.IsNull(manager.ActiveSettingsSource, "SettingsSource is not correct.");

            manager.SolutionClosed();

            Assert.IsNull(manager.ActiveSolution, "Solution was not closed.");
        }

        [TestMethod]
        public void TestOpen_SolutionWithSettings() {
            var fs = new MockFileSystem();
            fs.Files.Add(new MockFile(@"X:\Test.sln", FileCreator.BlankSolution));
            fs.Files.Add(new MockFile(@"X:\Test.settings", FileCreator.BlankSettings));
            ActivityLog.Clear();
            var manager = NewManager(fs: fs);

            var sln = new MockSolution(@"X:\Test.sln");
            manager.SolutionOpened(sln);

            Assert.AreSame(sln, manager.ActiveSolution, "ActiveSolution is not correct.");
            Assert.AreEqual(@"X:\Test.settings", manager.ActiveSettingsSource, true, "SettingsSource is not correct.");

            manager.SolutionClosed();

            Assert.IsNull(manager.ActiveSolution, "Solution was not closed.");
        }
    }
}
